using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using ST.Application.UserServices.Dtos;
using ST.Domain;
using ST.Domain.Entities;
using ST.Domain.IRepositories;

namespace ST.Application.UserServices
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;

        public UserService(IUserRepository userRepository,IMapper mapper)
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }

        public User CheckUser(string userName, string password)
        {
            return _userRepository.CheckUser(userName, password);
        }

        public async Task<PagedList<UserDto>> GetUserByDepartment(Guid departmentId, int startPage, int pageSize)
        {
            var pages = await _userRepository.LoadPageListAsync(startPage, pageSize,
                it => it.DepartmentId == departmentId, it => it.CreateTime);
            return _mapper.Map<PagedList<UserDto>>(pages);
        }

        public async Task<bool> InsertAsync(UserDto dto)
        {
            await _userRepository.InsertAsync(_mapper.Map<User>(dto), false);
            return await _userRepository.SaveAsync();
        }

        public async Task<bool> UpdateAsync(UserDto dto)
        {
            await _userRepository.UpdateAsync(_mapper.Map<User>(dto), false);
            return await _userRepository.SaveAsync();
        }

        public async Task DeleteBatchAsync(List<Guid> ids)
        {
            await _userRepository.DeleteAsync(o => ids.Contains(o.Id));
        }

        public async Task DeleteAsync(Guid id)
        {
            await _userRepository.DeleteAsync(id);
        }

        public async Task<UserDto> GetAsync(Guid id)
        {
            var user = await _userRepository.GetWithRoles(id);
            return _mapper.Map<UserDto>(user);
        }
    }
}